/* Copyright 2024 Coremail
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import notificationManager from '@ohos.notificationManager';
import wantAgent from '@ohos.app.ability.wantAgent';
import type { WantAgent } from '@ohos.app.ability.wantAgent';
import type Base from '@ohos.base';

/**
 * 通知栏管理
 */
export class NoticeManager {
  static noticeCount:number = 0;
  //是否申请了权限
  static hasRequest:boolean = false;
  static notify(title: string, text: string, briefText: string): void {
    if(!NoticeManager.hasRequest) {
      notificationManager.requestEnableNotification().then(()=>{
        NoticeManager.doNotify(title,text,briefText);
        NoticeManager.noticeCount++;
      }).catch(()=>{
        //拒绝的回调.
      })
      NoticeManager.hasRequest = true;
      return;
    }
    NoticeManager.doNotify(title,text,briefText);
    NoticeManager.noticeCount++;
  }

  private static doNotify( title: string, text: string, briefText: string): void {
    let wantAgentInfo: wantAgent.WantAgentInfo = {
      wants: [
        {
          deviceId: '',
          bundleName: 'cn.coremail.mailclient',
          abilityName: 'UnityAbility',
          action: '',
          entities: [],
          uri: '',
          parameters: {}
        }
      ],
      operationType: wantAgent.OperationType.START_ABILITY,
      requestCode: NoticeManager.noticeCount,
      wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]
    };

    wantAgent.getWantAgent(wantAgentInfo, (err: Base.BusinessError, data: WantAgent) => {
      if (err) {
        return;
      }
      let notificationRequest: notificationManager.NotificationRequest = {
        content: {
          notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
          normal: {
            title: title || "title",
            text: text || "text",
            additionalText: briefText || "dddd",
          },
        },
        id: NoticeManager.noticeCount,
        wantAgent: data,
      }
      notificationManager.publish(notificationRequest, (err: Base.BusinessError) => {
        if (err) {
          return;
        }
      });
    });
  }

  static cancel(id: number): void {
    notificationManager.cancel(id)
  }

  static cancelAll(): void {
    notificationManager.cancelAll()
  }
}